<?php

class wx
{
    private $_appId = 'wx6e9f935be224ef2e';
    private $_appSecret = 'fda90d889cf846234720ee5d414a336c';
    private $_uri = 'https://open.weixin.qq.com/connect/oauth2/';
    private $_redirectUrl = "http://jog-test.mobileapi.hupu.com/connect/wxcallback";

    public function authorizeUrl()
    {
        $state = md5($this->_appId . $this->_appSecret . time());
        $param = array(
            'appid' => $this->_appId,
            'redirect_uri' => $this->_redirectUrl,
            'response_type' => 'code',
            'scope' => 'snsapi_userinfo',
            'state' => $state
        );
        $param = http_build_query($param);
        return $this->_uri ."authorize?" . $param . "#wechat_redirect";
    }

    public function pubOpenIdUrl()
    {
        $state = md5($this->_appId . $this->_appSecret . time());
        $param = array(
            'appid' => $this->_appId,
            'redirect_uri' => $this->_redirectUrl . '?pub=1',
            'response_type' => 'code',
            'scope' => 'snsapi_base',
            'state' => $state
        );
        $param = http_build_query($param);
        return $this->_uri ."authorize?" . $param . "#wechat_redirect";
    }

    public function getToken($code, $state)
    {
        $param = array(
            'appid' => $this->_appId,
            'secret' => $this->_appSecret,
            'code' => $code,
            'grant_type' => 'authorization_code'
        );
        $param = http_build_query($param);
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . $param;
        $response = json_decode($this->http($url), true);
        return $response;
    }

    public function getUserInfo($token, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$token}&openid={$openid}";
        $userInfo = json_decode($this->http($url), true);
        return $userInfo;
    }

    private function http($url)
    {
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ci, CURLOPT_HEADER, FALSE);
        curl_setopt($ci, CURLOPT_URL, $url);
        curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE);
        $response = curl_exec($ci);
        curl_close($ci);
        return $response;
    }
}